package com.atguigui.leetcode;

import java.util.HashMap;

/**
 * 1161.最大层内元素和
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2022/7/31 20:16
 */
public class P1161MaximumLevelSumOfABinaryTree {
    public static void main(String[] args) {
        Solution solution = new P1161MaximumLevelSumOfABinaryTree().new Solution();
        // TO TEST
    }

    class Solution {

        private HashMap<Integer, Integer> map = new HashMap();

        public int maxLevelSum(TreeNode root) {
            getCode(root, 1);

            int ans = 0;
            int sun = Integer.MIN_VALUE;
            for (Integer integer : map.keySet()) {
                Integer value = map.get(integer);
                if (sun < value) {
                    sun = value;
                    ans = integer;
                }
                if (sun == value) {
                    ans = ans < integer ? ans : integer;
                }
            }

            return ans;
        }

        private void getCode(TreeNode root, int i) {
            if (root == null) {
                return;
            }


            Integer sum = map.getOrDefault(i, 0);
            sum += root.val;
            map.put(i, sum);

            i++;
            getCode(root.left, i);
            getCode(root.right, i);
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
